//
//  RingSubscribeListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2021/3/18.
//  Copyright © 2021 王洋. All rights reserved.
//
#import "RingSubscribeListCell.h"
#import "RingSubscribeSectionHeader.h"
#import "RingSubscribeSectionFooter.h"

#import "RingSubscribeDetailViewController.h"

#import "RingSubscribeListViewController.h"

@interface RingSubscribeListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <CommonSubscribeRingModel *>*dataArray;


@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation RingSubscribeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_applyList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)refreshParam {
    
    self.pageSize = 100;
    self.pageNum = 1;
    self.dataArray = @[].mutableCopy;
}

- (void)initView {
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(0);
    }];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    switch (self.dataArray[section].type) {
        case 1:{
            switch (self.dataArray[section].isReceive) {
                case 1:{
                    return 50;
                } break;
                case 2:{
                    return 14;
                } break;
                default:
                    break;
            }
        } break;
        case 2:{
            return 14;
        } break;
        case 3:{
            return 50;

        } break;
        default:
            break;
    }
    
//    if (self.dataArray[section].type == 2) {
//        return 14;
//    }
    return 14;
}

#pragma mark sectionheader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    RingSubscribeSectionHeader *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"RingSubscribeSectionHeader"];
    
    WEAKSELF
    [headView addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        RingSubscribeDetailViewController *vc = [[RingSubscribeDetailViewController alloc] init];
        vc.abId = weakSelf.dataArray[section].abId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    [headView fillWithModel:self.dataArray[section]];
    return  headView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    RingSubscribeSectionFooter *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"RingSubscribeSectionFooter"];
    [footerView fillWithModel:self.dataArray[section]];
    
    WEAKSELF
    footerView.RingSubscribeSectionFooterBlock = ^(RingSubscribeSectionFooterActionType type) {
      
        switch (type) {
            case RingSubscribeSectionFooterActionType_cache:{
                [weakSelf request_cacheRingWith:section];
            } break;
            default:
                break;
        }
    };
    
    return  footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 75;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    RingSubscribeDetailViewController *vc = [[RingSubscribeDetailViewController alloc] init];
    vc.abId = self.dataArray[indexPath.section].abId;
    [self.navigationController pushViewController:vc animated:YES];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RingSubscribeListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RingSubscribeListCellID"];
    [cell fillWithModel:self.dataArray[indexPath.section]];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
}


- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xF2F3F6);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"RingSubscribeListCell" bundle:nil] forCellReuseIdentifier:@"RingSubscribeListCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"RingSubscribeSectionHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:@"RingSubscribeSectionHeader"];

        [_tableview registerNib:[UINib nibWithNibName:@"RingSubscribeSectionFooter" bundle:nil] forHeaderFooterViewReuseIdentifier:@"RingSubscribeSectionFooter"];

//        _tableview.tableHeaderView
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_applyList];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_applyList];
        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}

- (void)request_applyList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];

    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [t setValue:@"2" forKey:@"isDel"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_ApplyRingList];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在请求预约列表"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];

        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                if ([list isKindOfClass:[NSArray class]]) {
                    if (weakSelf.pageNum == 1) {
                        weakSelf.dataArray = @[].mutableCopy;
                    }
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        CommonSubscribeRingModel *model = [CommonSubscribeRingModel modelWithDictionary:listDic];
                        [weakSelf.dataArray addObject:model];
                    }
                    
                    if (weakSelf.dataArray.count == 0) {
                        [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_EmptyView btnTitle:@"" didPressButton:^{
                        }];
                    }
                    
                    [weakSelf.tableview reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
}

//请求获取手环
- (void)request_cacheRingWith:(NSInteger)index {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_RingUpdate];
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.dataArray[index].abId forKey:@"abId"];
    [dic setValue:@"2" forKey:@"type"];

    [SVProgressHUD showWithStatus:@"正在提交"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];

                weakSelf.dataArray[index].type = 2;
                [weakSelf.tableview reloadData];
                
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

@end
